<template>
	<div>
		<head-top></head-top>	
		<div class="boxWrap">			
			<div class="analysis_bomb">
				<div class="col-sm-12 create_header">
					<img src="../../assets/img/smart_build_img.svg" alt="img" class="col-sm-1" style="width:70px;height:60px;"/>
					<div class="col-sm-11 text-left">
						<h5>智能建模</h5>
						<p class="create_words">
							通过智能建模,你只需要按需选择好数据的标签和特征列,就可以快速得到根据数据训练出的最佳模型,而且你也可以自由保存合适的模型用于后续的数据预测。
						</p>
					</div>
				</div>
			</div>
		</div>		
		<div class="col-sm-12 text-left create_tip_words">
			<p class="analysis_bomb text-center">					
				第一步：选择数据（对于聚类问题，请不要添加标签列）； 第二步：提交计算任务 ；第三步：保存相应模型。
			</p>
		</div>
		<div class="boxWrap">				
			<div class="analysis_bomb">
				<h4 class="text-left analysis_title" style="margin-bottom:20px;">选择要分析的数据</h4>
				<selectCol :col_detail="details.col_detail" :label_detail="model_tem_details.label_detail"></selectCol>
				<p class="text-center">
					<button class="build_task_sure btn" @click="buildTask()">开始建模</button>
				</p>
			</div>
		</div>
		<footerHtml></footerHtml>
		<div id="mask" v-if="seen"></div>
		<div class="bomb_box modeling_bomb" v-show="smartBomb">
			<img src="../../assets/img/loading.gif" alt="loading" class="loading_bomb"/>
			<p class="smart_task_title text-center">智能建模中...</p>
			<div class="clearfix task_inner">								
				<p class="text-left left">
					<span class="task_info_key">数据源:</span>
					<span class="task_info_val">{{details.title}}</span>
				</p>
				<p class="text-left right">
					<span class="task_info_key">建模类型:</span>
					<span class="task_info_val">{{model_type_val}}</span>
				</p>			
			</div>
			<div class="clearfix task_inner">
				<p class="text-left left">
					<span class="task_info_key">标签列:</span>
					<span class="task_info_val">{{label_type_val}}</span>
				</p>
				<p class="text-left right">
					<span class="task_info_key">特征列数:</span>
					<span class="task_info_val">{{details.column_number}}</span>
				</p>
			</div>
			<p class="text-center">
				<button class="data_info_run_back btn" @click="bombBoxHide()"><router-link :to="{name:'dashboard'}">转到后台运行</router-link></button></br>
				<span class="toDashTip">（任务状态可随后在工作台查看）</span>
			</p>
		</div>
	</div>	
</template>

<script>
	//引入公共模块
	import headTop from '@/components/headTop'
	import footerHtml from '@/components/footerHtml'
	import selectCol from '@/components/selectCol'
	import global_ from '@/components/global'
	//api	
	import {urlRunJob,urlDataDetail,urlSmartAnalyzation,urlModelDetail} from '../../api/api'
export default {
    name: 'task',   
    data(){
    	return { 
    		//控制弹框是否可见
    		seen:false,
    		smartBomb:false,
    		//返回的数据    
    		tag_col:'',
    		tag_type:'',
    		job_id:'',
    		model_type_val:'',
    		label_type_val:'',
    		details:{
    			title:'',
    			details:'',
	    		col_detail:'',
	    		column_number:'',
	    		
    		},
    		model_tem_details:{
    			label_detail:''
    		}
    	}
    },
    components:{
    	headTop,
    	footerHtml,
    	selectCol
    },   
    mounted(){
    	let sendData={
	 		id:this.$route.params.id
    	};
 		urlDataDetail(sendData).then(response => {
  			if(response.data.code==200){	  				
  				let resData=response.data.data;
	 			this.details.title=resData.title;
	    		this.details.feature=resData.feature;
	    		this.details.col_detail=resData.col_detail;
	    		this.details.column_number=resData.column_number;
  			}else if(response.data.code!=200){
  				console.log('获取数据失败')
  			}				    		
 		});
 		let	sendModelType={
	  		model_type:2
    	};		    	
		urlModelDetail(sendModelType).then(response => {
 			if(response.data.code==200){
 				let resData=response.data.data;
              	this.model_tem_details.label_detail=resData.label_detail;     				
 			}else{
 				alert('返回数据有误')
 			}
        })
    },
    methods: { 
    	bombBoxHide(){
    		this.seen=false;
	    	this.smartBomb=false;
    	},  
      	buildTask(){      		
			//创建任务的请求
			let tag_col_val=$('#foospe').children('li').attr('is_index'),	    			
    			colArr = [],	    		
    			colLi = $('#foo').children('li');
			$.each(colLi,function(i,n){
    			colArr.push($(n).attr('is_index'));		    			
    		});
    		//检查右侧框里有空值没拖拽，应 return false;(标签可以为空)
    		for(var i = 0 ;i<colArr.length;i++) {  
         		if(colArr[i] == "" || typeof(colArr[i]) == "undefined") {  
              		alert('数据没有选择完整');
                 	return false;
         		}
     		}  
     		//判断数组里面是否是空，如果为空就不执行。
     		if(colArr==''){
   				alert('数据没有选择完整');
                return false;
     		}
     		//把数组里面的字符串转成数字 eg:['1','2']=>[1,2]
       		let colArrEnd=JSON.parse('[' + String(colArr) + ']'),
			sendData={
				data_id:this.$route.params.id,
				tag_col:tag_col_val || '',
				cols:colArrEnd
			};
			urlSmartAnalyzation(sendData).then(response => {
     			if(response.data.code==200){
     				this.seen=true;
	    			this.smartBomb=true;
     				if(response.data.data.model_type==0){
     					this.model_type_val='回归模型'
     				}else if(response.data.data.model_type==1){
     					this.model_type_val='聚类模型'
     				}else{
     					this.model_type_val='分类模型'     					
     				}
     				if(response.data.data.label_type==0){
     					this.label_type_val='数值型'
     				}else if(response.data.data.label_type==1){
     					this.label_type_val='类别型'
     				}
     				this.job_id=response.data.data.job_id;
					let sendDataRun={
		    			job_id:this.job_id
		    		}
		            urlRunJob(sendDataRun).then(response => {
		     			if(response.data.code==200){
		     				this.linkSocket();
		     			}else{
		     				alert('抱歉，返回数据有误')
		     			}
			        })
     			}else if(response.data.code==201){    				
     				talert('创建失败');
     			}		
         	}).catch(error => {
         		if(error.response.data.code==401){
            		localStorage.clear();
            		this.$router.replace('/login');
				}
          	});	
		},
		linkSocket(){			
			let socket = io.connect(global_.urlSocket),
	            user = localStorage.getItem('username');
	        socket.emit('join', {'room': user});
			let _selfRun=this;
	        socket.on('my_response', function(msg) {		        	
	            //链接状态
	            if(msg.type==0){
	            	if(msg.type==0 && msg.code==1){
	            		console.log('链接成功')		            		
	            	}else if(msg.type==0 && msg.code!=1){
		                console.log('connect failed');
		            }
	            }
	            //已经加入到聊天室
	            if(msg.type==1){
	            	console.log(msg.data)
	            }
	            //所有人都能收到的消息
	            if(msg.type==2){
	            	console.log(msg.data)
	            }
	            //单播消息
	            if(msg.type==3){
	            	if(msg.code==0 && msg.type==3){
	            		console.log(msg.data)
	            	}else if(msg.code==2 && msg.type==3){	
	            		//进入到智能建模报告
	            		_selfRun.$router.push({name:'analysisResults',params: {id:_selfRun.job_id}})
	            	}
	            }
	        });
			
	        //接收广播
	        socket.on('broadcast', function(msg){
		            console.log(msg.data);
	        });
		}

  	}
}
</script>

<style lang="css">
	@import "../../assets/css/task.css"
</style>
<style lang="css">
	@import "../../assets/css/buildStep.css"
</style>


